package servlet;


import mongo.UserAccount;
import org.bson.Document;
import org.bson.types.ObjectId;

import com.mongodb.client.MongoCursor;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@WebServlet(description = "registerProcess", urlPatterns = { "/register" })
public class registerServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        
        String username=request.getParameter("username");
        String password1=request.getParameter("password1");
        String type = request.getParameter("type");

        UserAccount userAccount = new UserAccount();
        String loginUrl = "";
        
        try {
        	Boolean result = userAccount.isExistUser(username); //判断账号是否已经注册
            if(result){
            	request.setAttribute("error","学号/工号已存在！");
            	loginUrl = "/register.jsp";
            }else{
            	if(userAccount.isRegisterSuccess(username, password1, type)){ //注册账号是否成功
            		request.setAttribute("result","注册成功！");
            		loginUrl = "/login.jsp";
            	}else{
            		request.setAttribute("error","注册失败！请重试！");
            		loginUrl = "/register.jsp";
            	}
            }  
        }catch(Exception e){
            System.err.println( e.getClass().getName() + ": " + e.getMessage() );
            request.setAttribute("error","注册失败！请重试！");
            loginUrl = "/register.jsp";
        }
        request.getRequestDispatcher(loginUrl).forward(request, response);
    }
}